<template>
  <div class="activity-edit">
    <van-nav-bar title="编辑活动" left-arrow @click-left="onClickLeft" />

    <div class="form-container">
      <van-form @submit="onSubmit" v-if="!loading">
        <!-- 活动标题 -->
        <van-cell-group inset>
          <van-field v-model="formData.title" name="title" label="活动标题" placeholder="请输入活动标题"
            :rules="[{ required: true, message: '请填写活动标题' }]" />
        </van-cell-group>

        <!-- 活动封面 -->
        <van-cell-group inset>
          <van-field name="coverImage" label="活动封面" :rules="[{ required: true, message: '请上传活动封面' }]">
            <template #input>
              <van-uploader v-model="formData.coverImages" :max-count="1" :after-read="afterRead" />
            </template>
          </van-field>  
        </van-cell-group>

        <!-- 活动类型 -->
        <van-cell-group inset>
          <van-field v-model="formData.type" name="type" label="活动类型" placeholder="请选择活动类型" readonly clickable
            :rules="[{ required: true, message: '请选择活动类型' }]" @click="showTypePopup = true" />
          <van-popup v-model:show="showTypePopup" position="bottom">
            <van-picker :columns="activityTypes" @confirm="onTypeConfirm" @cancel="showTypePopup = false"
              title="选择活动类型" />
          </van-popup>
        </van-cell-group>

        <!-- 活动时间 -->
        <van-cell-group inset>
          <van-field v-model="formData.startTime" name="startTime" label="开始时间" placeholder="请选择开始时间" readonly
            clickable :rules="[{ required: true, message: '请选择开始时间' }]" @click="showStartTimePicker = true" />
          <van-popup v-model:show="showStartTimePicker" position="bottom">
            <van-datetime-picker type="datetime" :min-date="new Date()" :value="startDate"
              @confirm="onStartTimeConfirm" @cancel="showStartTimePicker = false" title="选择开始时间" />
          </van-popup>
        </van-cell-group>

        <van-cell-group inset>
          <van-field v-model="formData.endTime" name="endTime" label="结束时间" placeholder="请选择结束时间" readonly clickable
            :rules="[{ required: true, message: '请选择结束时间' }]" @click="showEndTimePicker = true" />
          <van-popup v-model:show="showEndTimePicker" position="bottom">
            <van-datetime-picker type="datetime" :min-date="startDate" :value="endDate" @confirm="onEndTimeConfirm"
              @cancel="showEndTimePicker = false" title="选择结束时间" />
          </van-popup>
        </van-cell-group>

        <!-- 活动地点 -->
        <van-cell-group inset>
          <van-field v-model="formData.location" name="location" label="活动地点" placeholder="请输入活动地点"
            :rules="[{ required: true, message: '请填写活动地点' }]" />
        </van-cell-group>

        <!-- 活动描述 -->
        <van-cell-group inset>
          <van-field v-model="formData.description" name="description" label="活动描述" type="textarea" rows="4"
            placeholder="请输入活动描述" :rules="[{ required: true, message: '请填写活动描述' }]" />
        </van-cell-group>

        <!-- 路线说明 -->
        <van-cell-group inset>
          <van-field v-model="formData.routeDescription" name="routeDescription" label="路线说明" type="textarea" rows="4"
            placeholder="请输入路线说明" :rules="[{ required: true, message: '请填写路线说明' }]" />
        </van-cell-group>

        <!-- 提交按钮 -->
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            保存修改
          </van-button>
        </div>
      </van-form>

      <div class="loading-container" v-else>
        <van-loading type="spinner" color="#8a2be2" size="36px">加载中...</van-loading>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast, showSuccessToast } from 'vant';
import dayjs from 'dayjs';
import { useActivityStore } from '@/stores/activity';

const router = useRouter();
const route = useRoute();
const activityStore = useActivityStore();
const activityId = computed(() => route.params.id as string);
const loading = ref(true);

// 表单数据
const formData = ref({
  title: '',
  coverImages: [],
  type: '',
  startTime: '',
  endTime: '',
  location: '',
  description: '',
  routeDescription: ''
});

// 活动类型选择
const showTypePopup = ref(false);
const activityTypes = ['休闲骑行', '山地骑行', '公路骑行', '夜骑', '亲子骑行', '环湖骑行', '长途骑行'];

const onTypeConfirm = (value) => {
  formData.value.type = value;
  showTypePopup.value = false;
};

// 时间选择
const showStartTimePicker = ref(false);
const showEndTimePicker = ref(false);
const startDate = computed(() => {
  return formData.value.startTime ? new Date(formData.value.startTime) : new Date();
});
const endDate = computed(() => {
  return formData.value.endTime ? new Date(formData.value.endTime) : new Date();
});

const onStartTimeConfirm = (value) => {
  formData.value.startTime = dayjs(value).format('YYYY-MM-DD HH:mm');
  showStartTimePicker.value = false;
};

const onEndTimeConfirm = (value) => {
  formData.value.endTime = dayjs(value).format('YYYY-MM-DD HH:mm');
  showEndTimePicker.value = false;
};

// 图片上传
const afterRead = (file) => {
  // 这里应该调用上传图片的API
  // 模拟上传成功
  file.status = 'done';
  file.message = '上传成功';
  console.log('上传图片:', file);
};

// 获取活动详情
const fetchActivityDetail = async () => {
  try {
    loading.value = true;
    // 这里应该调用获取活动详情的API
    // const result = await activityStore.getActivityDetail(activityId.value);

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 模拟数据
    const mockData = {
      id: activityId.value,
      title: '测试活动 ' + activityId.value,
      coverImages: [
        {
          url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg',
          isImage: true,
          status: 'done',
          message: '上传成功',
          name: 'image.jpg'
        }
      ],
      type: '休闲骑行',
      startTime: dayjs().add(1, 'day').format('YYYY-MM-DD HH:mm'),
      endTime: dayjs().add(1, 'day').add(3, 'hour').format('YYYY-MM-DD HH:mm'),
      location: '杭州市西湖区',
      description: '这是一个测试活动的描述，包含活动的详细信息。',
      routeDescription: '从A点出发，经过B点，最终到达C点。全程约30公里。'
    };

    // 填充表单数据
    formData.value = mockData;

  } catch (error) {
    console.error('获取活动详情失败:', error);
    showToast('获取活动详情失败');
  } finally {
    loading.value = false;
  }
};

// 表单提交
const onSubmit = async (values) => {
  console.log('表单数据:', values);

  try {
    // 这里应该调用更新活动的API
    // const result = await activityStore.updateActivity(activityId.value, formData.value);

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));

    showSuccessToast('活动更新成功');
    router.push(`/activity/detail/${activityId.value}`);
  } catch (error) {
    console.error('更新活动失败:', error);
    showToast('保存失败，请重试');
  }
};

// 返回上一页
const onClickLeft = () => {
  router.back();
};

// 页面加载时获取活动详情
onMounted(() => {
  fetchActivityDetail();
});
</script>

<style scoped>
.activity-edit {
  padding-bottom: 20px;
}

.form-container {
  padding: 16px 0;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

:deep(.van-cell-group--inset) {
  margin: 12px 16px;
}

:deep(.van-uploader) {
  padding-top: 8px;
}

:deep(.van-uploader__upload) {
  width: 80px;
  height: 80px;
}

:deep(.van-uploader__preview-image) {
  width: 80px;
  height: 80px;
}
</style>


